import React, {useState, useEffect} from 'react'
import {
	Form,
	Row,
	Col,
	Button,
	Space,
	TreeSelect,
	message,
	Spin,
	Select,
} from 'antd'
import {connect, history} from 'umi'
import moment from 'moment'
import styles from './index.less'
import {
	FormSelect,
	FormInput,
	FormRadio,
	FormTime,
} from '@/components/SearchForm/SearchFormItem'
import SelectScheme from '../common/selectScheme'
import CustomTable from '@/components/Table'
import {GlobalState} from '@/models/global'
import {addOrder} from '@/service/order'
import {formatDate} from '@/utils/common/dateFilter'
import {getCompany} from '@/service/common'
import {getLists, getClueLists, getBDLists} from '@/service/channel'
import {
	getDdDriverDetail,
	getDdDriverTableList,
} from '@/service/customer/driver'
import {translateDataToTree} from '@/utils/common'
import {getCookie} from '@/utils/cookie'

export interface Props {
	global: GlobalState
	dispatch: any
	location: any
	user: any
}
const fieldNames = {
	label: 'name',
	value: 'id',
	id: 'id',
	pId: 'parentId',
}
const formItemLayout = {
	labelCol: {
		xs: {span: 24},
		sm: {span: 10},
	},
	wrapperCol: {
		xs: {span: 24},
		sm: {span: 14},
	},
}

// 承租方类型
const lesseeType = [
	{text: '司机', value: 1},
	{text: '线索', value: 2},
]
function AddOrder({global: {currentRoute}, dispatch, location, user}: Props) {
	const [loading, setLoading] = useState(false)
	const [lessorsName, setLessorsName] = useState<any>([]) // 所属公司
	const [dirverInfo, setDirveInfo] = useState<any>() // 司机
	// const [customerName,setCustomerName] = useState() // 客户名
	const adress: string = '' // 联系地址
	const [phone, setPhone] = useState() // 联系电话
	const [selectScheme, setSelectScheme] = useState(false) // 选择商品方案弹窗
	const [plan, setPlan] = useState<any>({
		commodityNo: '',
		commodityName: '',
		id: '',
		rentTypeId: '',
		rentTypeName: '',
		leaseTerm: '',
		rentAmount: '',
		renewRentAmount: '',
		advancePaymentAmount: '',
		balancePaymentAmount: '',
		schemeDesc: '',
		depositAmount: '',
		mortgageAmount: '',
		brandId: '',
		awardCode: '',
	}) // 商品方案
	const [channelList, setChannelList] = useState() // 渠道
	const [BDList, setBDList] = useState() // 跟单BD
	const [form] = Form.useForm()
	const [shoppingList, setShoppingList] = useState<any>([]) // 商品方案列表
	const [leaseTermer, setLeaseTermer] = useState() // 租期
	const [channelIds, setChannelIds] = useState() // 渠道id
	const [bdIds, setBdIds] = useState() // bdid
	const [cityIds, setCityIds] = useState() // 城市id
	const [cityNames, setCityNames] = useState() // 城市名字
	const [companyIds, setCompanyIds] = useState() // 公司ID
	const [lesseeIds, setLesseeIds] = useState() // 承租方id
	const [ditchType, setDitchType] = useState<any>() // 渠道类型
	const [BDStaue, setBDStaue] = useState<any>() // BD状态 BDStaue==='1'表示不存在
	const [BDstatus, setBDstatus] = useState(false) // BD是否可选
	const [codeStaue, setCodeStaue] = useState<any>() // code状态 codeStaue==='1'表示不存在
	const [tenantryType, setTenantryType] = useState(1) // 承租方类型
	const [tenantryStatua, setTenantryStatua] = useState(2) // 默认承租方不可选，选择公司后才可选
	const [orgStatus, setOrgStatus] = useState(1) // 所属公司状态
	const [codeList, setCodeList] = useState<any>([]) // code码
	const [codeType, setCodeType] = useState(1) // code码状态
	const [channelState, setChannelState] = useState('2') //  渠道状态 channelState==='1'表示不存在
	const [startTimeState, setStartTimeState] = useState(true) // 租赁开始时间状态
	// 付款方式
	// const [dict, setDict] = useState({
	// 	order_payment_method: [], // 订单付款方式
	// })
	const [payType, setPayType] = useState([
		{text: '月付', value: 1, state: false},
		{text: '两月付', value: 2, state: false},
		{text: '季付', value: 3, state: false},
		{text: '半年付', value: 6, state: false},
		{text: '年付', value: 12, state: false},
		{text: '一次性结清', value: -1, state: false},
	])
	// const [channelStatus,setChannelStatus] = useState(false) // 渠道是否可选
	const [valueNo, setValueNo] = useState<string>()

	const columns = [
		// {
		// 	title: '商品方案ID',
		// 	dataIndex: 'commodityNo',
		// 	width:250
		// },
		{
			title: '商品方案名称',
			dataIndex: 'commodityName',
			width: 200,
		},
		{
			title: '主体',
			dataIndex: 'subjectName',
			width: 100,
		},
		{
			title: '公司',
			dataIndex: 'affiliatedCompany',
			width: 100,
		},
		{
			title: '城市',
			dataIndex: 'cityName',
			width: 100,
		},
		{
			title: '开始时间',
			dataIndex: 'beginTime',
			width: 100,
		},
		{
			title: '结束时间',
			dataIndex: 'endTime',
			width: 100,
		},
		{
			title: '品牌/车型/车系',
			dataIndex: 'brandInfo',
			width: 150,
		},
		{
			title: '星级',
			dataIndex: 'carStar',
			width: 100,
		},
		{
			title: '订单类型',
			dataIndex: 'rentTypeName',
			width: 150,
		},
		{
			title: '租期',
			dataIndex: 'leaseTerm',
			width: 100,
			render: (text: any) => (
				<>{text > 0 ? <span>{text}</span> : <span>--</span>}</>
			),
		},
		{
			title: '押金',
			dataIndex: 'mortgageAmount',
			width: 100,
			render: (text: any) => (
				<>{text > 0 ? <span>{text}</span> : <span>--</span>}</>
			),
		},
		{
			title: '定金',
			dataIndex: 'depositAmount',
			width: 100,
			render: (text: any) => (
				<>{text > 0 ? <span>{text}</span> : <span>--</span>}</>
			),
		},
		{
			title: '月租金(新签)',
			dataIndex: 'rentAmount',
			width: 150,
			render: (text: any) => (
				<>{text > 0 ? <span>{text}</span> : <span>--</span>}</>
			),
		},
		{
			title: '月租金(续签)',
			dataIndex: 'renewRentAmount',
			width: 150,
			render: (text: any) => (
				<>{text > 0 ? <span>{text}</span> : <span>--</span>}</>
			),
		},
		{
			title: '首付款',
			width: 100,
			dataIndex: 'advancePaymentAmount',
			render: (text: any) => (
				<>{text > 0 ? <span>{text}</span> : <span>--</span>}</>
			),
		},
		{
			title: '尾款',
			width: 100,
			dataIndex: 'balancePaymentAmount',
			render: (text: any) => (
				<>{text > 0 ? <span>{text}</span> : <span>--</span>}</>
			),
		},
		{
			title: '方案状态',
			dataIndex: 'schemeStatus',
			width: 150,
		},
		{
			title: '审核状态',
			dataIndex: 'auditStatus',
			width: 150,
		},
	]
	// 获取BD列表
	const getBDInfo = (value: any) => {
		getBDLists(value).then((res: any) => {
			if (res?.success) {
				setBDList(res?.data)
			}
		})
	}
	// 渠道选择
	const channelChange = (_e: any, option: any) => {
		form.setFieldsValue({
			channelName: option?.ditchName,
			channelBdName: '',
		})
		setChannelIds(option?.id)
		setDitchType(option?.channelType)
		const typeName = option?.channelType?.split(',')[0]
		const typeValue = option?.channelType?.split(',')[1]
		// 如果渠道类型为车司，不展示code 类型为司忒司 普推司需要展示BD
		if (typeName === 'Sp_Channel_Type') {
			form.setFieldsValue({
				channelCode: '',
			})
			setCodeList(option?.code) // 车司的code是数组需要选择
			setCodeType(2)
			setBDStaue('1')
			setCodeStaue('2')
		} else if (typeName === 'Cs_Channel_Type') {
			setBDStaue('1')
			setCodeStaue('1')
		} else if (typeName === 'Zy_Channel_Type') {
			// form.setFieldValue('channelCode', option?.ditchVo?.code[0].code,)
			if (typeValue === '3') {
				// 自营bd直接带出code码只有一个
				form.setFieldsValue({
					channelCode: option?.code[0].code,
				})
				setCodeType(1)
				setBDStaue('1')
				setCodeStaue('2')
			} else {
				form.setFieldsValue({
					channelCode: '',
				})
				setBDStaue('2')
				setCodeStaue('2')
				setBDstatus(false)
				const ids = form.getFieldValue('orgId')
				getBDInfo({orgId: ids})
			}
		}
	}
	// 获取渠道列表
	const getChannelInfo = (value: any) => {
		const id = form.getFieldValue('orgId')
		const obj: any = {
			driverId: value,
			orgId: id,
		}
		// 有value就给BD赋值没有给渠道赋值
		getLists(obj).then((res: any) => {
			if (res?.success) {
				const {query} = location
				if (query?.id) {
					channelChange('', res?.data[0])
				} else {
					setChannelList(res?.data)
				}
			}
		})
	}
	// 获取线索列表
	const getClueInfo = (value: any) => {
		const ids = form.getFieldValue('orgId')
		const obj: any = {
			id: value?.id,
			orgId: ids || value?.ord,
		}
		getClueLists(obj).then((res: any) => {
			if (res?.success) {
				if (value?.id) {
					const list = res?.data
					list?.forEach((res1: any) => {
						if (res1?.source <= 3) {
							form.setFieldsValue({
								dirverInfo: res1?.username,
								customerName: res1?.username,
								lesseeAddress: '',
								lesseeTel: res1?.phone,
								channelName: res1?.ditchVo?.ditchName,
								channelBdName: res1?.ditchVo?.followUserName,
								channelCode: res1?.ditchVo?.code[0].code,
							})
						} else {
							form.setFieldsValue({
								customerName: res1?.username,
								dirverInfo: res1?.username,
								lesseeAddress: '',
								lesseeTel: res1?.phone,
								channelName: res1?.ditchVo?.ditchName,
								channelCode:
									res1?.ditchVo?.code?.lenth > 0
										? res1?.ditchVo?.code[0].code
										: '',
							})
						}
						setBdIds(res1?.ditchVo?.followUser)
						setLesseeIds(res1?.id)
						setCityIds(res1?.cityId)
						setCityNames(res1?.cityName)
						setPhone(res1?.phone)
						setChannelIds(res1?.ditchVo?.code?.[0]?.id)
						setDitchType(res1?.ditchVo?.channelType)
						const typeName =
							res1?.ditchVo?.channelType?.split(',')[0]
						const typeValue =
							res1?.ditchVo?.channelType?.split(',')[1]
						if (res1?.source <= 3) {
							setCodeType(1)
							setBDStaue('2')
							setBDstatus(true)
							setCodeStaue('2')
							setChannelState('1')
						} else {
							setChannelState('2')
							setBDstatus(true)
							// 如果渠道类型为车司，不展示code 类型为司忒司 普推司需要展示BD
							if (typeName === 'Sp_Channel_Type') {
								setCodeList(res1?.ditchVo?.code) // 车司的code是数组需要选择
								setBDStaue('2')
								setCodeStaue('2')
								setCodeType(2)
							} else if (typeName === 'Cs_Channel_Type ') {
								setBDStaue('2')
								setCodeStaue('1')
							} else if (typeName === 'Zy_Channel_Type') {
								setBDStaue('2')
								if (typeValue === '3') {
									// 自营bd直接带出code码只有一个
									form.setFieldsValue({
										channelCode:
											res1?.ditchVo?.code[0]?.code,
										channelBdName:
											res1?.ditchVo?.followUserName,
									})
									setBDstatus(true)
									setCodeStaue('2')
									setCodeType(1)
								} else {
									form.setFieldsValue({
										channelCode:
											res1?.ditchVo?.code[0]?.code,
										channelBdName:
											res1?.ditchVo?.followUserName,
									})
									setBDstatus(true)
									setCodeStaue('2')
									// getBDInfo({orgId:value?.ord})
								}
							}
						}
					})
				} else {
					const list = res?.data
					setDirveInfo(list)
				}
			}
		})
	}

	// 提交
	const onFinish = () => {
		setLoading(true)
		const value = form.getFieldsValue()
		const dtat = {
			// snapshoot:plan.toString(), // 商品方案所有信息
			order: {
				lesseeType: value?.lesseeType, // 承租方类型
				lessorId: companyIds, // 出租方-id
				lessorName: value?.lessorName, // 出租方-名字
				lesseeId: lesseeIds, // 承租方-id
				lesseeName: value?.customerName, // 承租方-名字
				lesseeAddress: value?.lesseeAddress, // 承租方地址
				lesseeTel: value?.lesseeTel, // 承租方电话
				channelId: channelIds === -1 ? '' : channelIds, // 渠道-id
				channelName: value?.channelName, // 渠道-名称
				cityId: cityIds, // 城市-id
				cityName: cityNames, // 城市-名字
				companyId: companyIds, // 公司-ID
				companyName: value?.lessorName, // 公司-名字
				channelType: ditchType, // 渠道类型-id
				channelTypename: '', // 渠道类型-名称
				channelCode: value?.channelCode, // 渠道code
				channelBdId: bdIds, // 渠道BD-id
				channelBdName: value?.channelBdName, // 渠道BD-名称
			},
			plan: {
				planId: plan?.id, // 方案ID
				planNo: plan?.commodityNo, // 方案编号
				planName: plan?.commodityName, // 方案名称
				rentType: plan?.rentTypeId, // 订单类型ID
				rentTypename: plan?.rentTypeName, // 订单类型名称
				tenancy: plan?.leaseTerm, // 租期
				planFeeList: [{}], // 费用项
				modelName: plan?.brandId, // 车牌/车型/车系 id
				applicableGoods: plan?.brandInfo, // 车牌/车型/车系 名称
				subjectId: plan?.subjectId, // 主体ID
				subjectName: plan?.subjectName, // 主体名称
				affiliatedCompanyId: plan?.affiliatedCompanyId, // 公司ID
				affiliatedCompany: plan?.affiliatedCompany, // 公司名称
				cityId: plan?.cityId, // 城市ID
				cityName: plan?.cityName, // 城市名称
				beginTime: plan?.beginTime, // 开始时间
				endTime: plan?.endTime, // 结束时间
				carStar: plan?.carStar, // 星级
				carStarId: plan?.carStarId, // 星级
			},
			paymentMethod: value?.paymentMethod?.toString(),
			paymentMethodname: '',
			startTime: formatDate(value?.startTime, 'YYYY-MM-DD HH:mm:ss'),
			remark: value?.remark,
		}
		payType?.forEach((res: any) => {
			if (res?.value === value?.paymentMethod) {
				// eslint-disable-next-line no-return-assign
				dtat.paymentMethodname = res?.text
			}
		})
		// 定金
		const depositAmount = {
			feeItemCode: '1',
			feeItemName: '定金',
			feeItemAmount: Number(plan?.depositAmount),
		}
		// 押金
		const mortgageAmount = {
			feeItemCode: '2',
			feeItemName: '押金',
			feeItemAmount: Number(plan?.mortgageAmount),
		}
		// 新签
		const newSignature = {
			feeItemCode: '3',
			feeItemName: '月租金(新签)',
			feeItemAmount: Number(plan?.rentAmount),
		}
		// 续签
		const oldSignature = {
			feeItemCode: '4',
			feeItemName: '月租金(续签)',
			feeItemAmount: Number(plan?.renewRentAmount),
		}
		// 首款
		const downPayments = {
			feeItemCode: '5',
			feeItemName: '首款',
			feeItemAmount: Number(plan?.advancePaymentAmount),
		}
		// 尾款
		const balancePayment = {
			feeItemCode: '6',
			feeItemName: '尾款',
			feeItemAmount: Number(plan?.balancePaymentAmount),
		}
		dtat.plan.planFeeList = []
		dtat.plan.planFeeList.push(depositAmount)
		dtat.plan.planFeeList.push(mortgageAmount)
		if (plan.rentTypeId === '1' || plan.rentTypeId === '3') {
			dtat.plan.planFeeList.push(newSignature)
			dtat.plan.planFeeList.push(oldSignature)
		} else if (plan.rentTypeId === '2' || plan.rentTypeId === '4') {
			dtat.plan.planFeeList.push(newSignature)
			dtat.plan.planFeeList.push(downPayments)
			dtat.plan.planFeeList.push(balancePayment)
		} else if (plan.rentTypeId === '5') {
			dtat.plan.planFeeList.push(newSignature)
			dtat.plan.planFeeList.push(balancePayment)
		}
		addOrder(dtat).then((res: any) => {
			if (res.success) {
				setLoading(false)
				history.push('/order/list')
			} else {
				setLoading(false)
			}
		})
	}
	const onCancel = () => {
		dispatch({
			type: 'global/deleteTabs',
			payload: currentRoute,
		})
		history.goBack()
	}
	const [companyData, setCompanyData] = useState<any>()
	/** 获取所属公司数据 */
	const onCompany = () => {
		getCompany({merchantId: user?.orgId}).then((res: any) => {
			const list = translateDataToTree(res?.data)
			setCompanyData(list as any)
		})
	}
	// 获取司机信息
	const getDirveInfo = (name: string) => {
		const id = form.getFieldValue('orgId')
		const queryData: any = {name}
		if (window.apiPrefixUri) {
			queryData.pageNum = 1
			queryData.pageSize = 100
			queryData.orgId = id || ''
		} else {
			queryData.current = 1
			queryData.size = 100
			queryData.groupOrgId = id || ''
			queryData.isDdOrder = 1
		}
		getDdDriverTableList(queryData).then((res: any) => {
			if (window.apiPrefixUri) {
				setDirveInfo(res?.data)
			} else {
				setDirveInfo(res?.data?.records)
			}
		})
	}
	useEffect(() => {
		// getDict(
		//   {
		//     dictKeys: [
		//       'order_payment_method', // 订单付款方式
		//     ],
		//   },
		//   (res:any) => {
		//     setDict(res)
		//   },
		// );
		// 判断页面是否带参数过来
		const {query} = location
		if (query?.id) {
			const dataInfo = {
				id: query?.id,
				ord: query?.orgID,
			}
			getClueInfo(dataInfo)
			setOrgStatus(2) // 所属公司不可编辑
			form.setFieldValue('lesseeType', 2)
			form.setFieldValue('orgId', query?.orgName)
			form.setFieldValue('lessorName', query?.orgName)
			setCompanyIds(query?.orgID)
			setTenantryType(2)
		} else {
			form.setFieldValue('lesseeType', 1)
			onCompany() // 获取公司列表
		}
		const list: any = []
		list.push(Number(getCookie('orgId')))
		setLessorsName(list)
		form.setFieldValue('paymentMethod', 1)
	}, [])
	// 所属公司选中事件
	const treeSelect = (_value: any, option: any) => {
		setShoppingList([]) // 清空商品方案
		setCompanyIds(option?.id)
		setStartTimeState(true)
		form.setFieldsValue({
			lessorName: option?.name,
			dirverInfo: '',
			customerName: '',
			lesseeAddress: '',
			lesseeTel: '',
			channelName: '',
			channelBdName: '',
			channelCode: '',
			startTime: '',
			endTime: '',
		})
		if (tenantryType === 1) {
			getDirveInfo('') // 获取司机列表信息
			getChannelInfo('') // 获取渠道列表
		} else {
			const {query} = location
			const dataInfo = {
				id: query?.id,
				ord: query?.orgID,
			}
			getClueInfo({dataInfo}) // 获取线索列表
		}
	}

	// 司机信息改变
	const dirveChange = (_e: any, option: any) => {
		if (option) {
			getDdDriverDetail({
				orgId: option?.orgId,
				driverId: option?.driverId,
			}).then((res) => {
				if (res?.success) {
					form.setFieldsValue({
						customerName: option?.name,
						lesseeAddress: res?.data?.address,
						lesseeTel: option?.tel,
						channelName: '',
						channelBdName: '',
						channelCode: '',
					})
					setChannelState('2')
					setLesseeIds(option?.driverId)
					setCityIds(option?.cityId)
					setCityNames(option?.cityName || option?.cityIdDesc)
					setPhone(option?.phone || option?.tel)
				}
			})
		} else {
			form.setFieldsValue({
				customerName: '',
				lesseeAddress: '',
				lesseeTel: '',
				channelName: '',
				channelBdName: '',
				channelCode: '',
			})
		}
	}
	// 线索信息该变

	const dirveChanges = (_e: any, option: any) => {
		// 如果线索来源是 58同城 公众号 客服进线 没有渠道，直接显示跟单BD和code
		if (option?.source <= 3) {
			form.setFieldsValue({
				customerName: option?.username,
				lesseeAddress: '',
				lesseeTel: option?.phone,
				channelName: '',
				channelBdName: option?.ditchVo?.followUserName,
				channelCode: option?.ditchVo?.code[0]?.code,
			})
		} else {
			form.setFieldsValue({
				customerName: option?.username,
				lesseeAddress: '',
				lesseeTel: option?.phone,
				channelName: option?.ditchVo?.ditchName || '',
				channelBdName: option?.ditchVo?.followUserName,
				channelCode: option?.ditchVo?.code[0]?.code,
			})
		}
		setBdIds(option?.ditchVo?.followUser)
		setCodeList(option?.ditchVo?.code) // 给code码赋值
		setChannelIds(option?.ditchVo?.id)
		setDitchType(option?.ditchVo?.channelType)
		const typeName = option?.ditchVo?.channelType?.split(',')[0]
		const typeValue = option?.ditchVo?.channelType?.split(',')[1]
		// 如果渠道类型为车司，不展示code 类型为司忒司 普推司需要展示BD
		if (option?.source <= 3) {
			setCodeType(1)
			setBDStaue('2')
			setBDstatus(true)
			setCodeStaue('2')
			setChannelState('1')
		} else {
			setChannelState('2')
			setBDstatus(false)
			if (typeName === 'Sp_Channel_Type') {
				setBDStaue('2')
				setCodeStaue('2')
				setCodeType(1)
				setBDstatus(true)
				form.setFieldsValue({
					channelCode: option?.ditchVo?.code[0]?.code,
				})
			} else if (typeName === 'Cs_Channel_Type ') {
				setBDStaue('2')
				setCodeStaue('1')
				setBDstatus(false)
			} else if (typeName === 'Zy_Channel_Type') {
				if (typeValue === '3') {
					form.setFieldsValue({
						channelCode: option?.ditchVo?.code[0]?.code,
						channelBdName: option?.ditchVo?.followUserName,
					})
					setBDstatus(true)
					setCodeStaue('2')
					setCodeType(1)
					setBDStaue('2')
				} else {
					// form.setFieldsValue({
					// 	channelBdName:'',
					// })
					setBDstatus(true)
					setBDStaue('2')
					setCodeStaue('2')
					// const ids = form.getFieldValue('orgId')
					// getBDInfo({orgId:ids})
				}
			}
		}
		setLesseeIds(option?.id)
		setCityIds(option?.cityId)
		setCityNames(option?.cityName || option?.cityIdDesc)
		setPhone(option?.phone)
		// getChannelInfo(option?.newDriverId)
	}

	// BD选择
	const BDChange = (_e: any, option: any) => {
		setCodeType(1)
		form.setFieldsValue({
			channelBdName: option?.ditchName,
			channelCode: option?.code[0]?.code,
		})
		setBdIds(option?.id)
	}
	// 选择商品方案
	const selectOrder = (value: any) => {
		setStartTimeState(false)
		form.setFieldValue('startTime', '')
		form.setFieldValue('endTime', '')
		// 根据商品方案种的租期来判断付款方式是否可以选择
		if (value?.leaseTerm <= 1) {
			payType?.forEach((res1: any, index: number) => {
				if (res1?.value === 1) {
					payType[index].state = false
				} else {
					payType[index].state = true
				}
			})
		} else if (value?.leaseTerm === 2) {
			payType?.forEach((res1: any, index: number) => {
				if (res1?.value === 1 || res1?.value === 2) {
					payType[index].state = false
				} else {
					payType[index].state = true
				}
			})
		} else if (value?.leaseTerm >= 3 && value?.leaseTerm < 6) {
			payType?.forEach((res1: any, index: number) => {
				if (
					res1?.value === 1 ||
					res1?.value === 2 ||
					res1?.value === 3
				) {
					payType[index].state = false
				} else {
					payType[index].state = true
				}
			})
		} else if (value?.leaseTerm >= 6 && value?.leaseTerm < 12) {
			payType?.forEach((res1: any, index: number) => {
				if (
					res1?.value === 1 ||
					res1?.value === 2 ||
					res1?.value === 3 ||
					res1?.value === 6
				) {
					payType[index].state = false
				} else {
					payType[index].state = true
				}
			})
		} else if (value?.leaseTerm >= 12) {
			payType?.forEach((res1: any, index: number) => {
				if (
					res1?.value === 1 ||
					res1?.value === 2 ||
					res1?.value === 3 ||
					res1?.value === 6 ||
					res1?.value === 12
				) {
					payType[index].state = false
				} else {
					payType[index].state = true
				}
			})
		}
		payType[5].state = false // 一次性结清永远可选
		setPayType(payType)
		form.setFieldValue('plan', value?.commodityNo)
		setPlan(value)
		const data = []
		data.push(value)
		setShoppingList(data)
		if (value?.leaseTerm) {
			setLeaseTermer(value?.leaseTerm)
		}
	}
	// 选择租赁开始日
	const timechange = (value: any) => {
		const time = formatDate(value, 'YYYY-MM-DD HH:mm:ss')
		let lease: number = 0
		if (leaseTermer) {
			lease = -leaseTermer
		}
		const date = moment(new Date(time))
			.subtract(lease, 'months')
			.format('YYYY-MM-DD ')
		const dates = moment(new Date(date))
			.subtract(1, 'days')
			.format('YYYY-MM-DD ')
		form.setFieldValue('endTime', dates)
	}
	// 切换承租方信息，清空下面所选司机名-客户信息-渠道信息
	const clearUserInfo = () => {
		form.setFieldsValue({
			channelBD: '',
			channelCode: [],
			lesseeTel: '',
			lesseeAddress: '',
			customerName: '',
			dirverInfo: '',
			channelName: '',
		})
	}
	// 获取采购下拉数据

	const handleSearch = (newValue: string) => {
		if (newValue) {
			getDirveInfo(newValue)
		} else {
			setDirveInfo([])
		}
	}
	const handleChange = (newValue: string, option: any) => {
		setValueNo(newValue)
		dirveChange(newValue, option)
	}
	return (
		<Spin spinning={loading}>
			<div className={styles.page}>
				<Form
					form={form}
					{...formItemLayout}
					onFinish={onFinish}
					autoComplete="off">
					<div className={styles.lease}>
						<p className={styles.title}>
							<span>出租/承租方信息</span>
						</p>
						<Row gutter={24}>
							<Col span={8}>
								<Form.Item label="所属公司" name="orgId">
									<TreeSelect
										// style={{width: '100%'}}
										dropdownStyle={{
											maxHeight: 400,
											overflow: 'auto',
										}}
										disabled={orgStatus === 2}
										treeDefaultExpandAll
										showCheckedStrategy="SHOW_ALL"
										fieldNames={fieldNames}
										treeDataSimpleMode
										treeData={companyData}
										value={lessorsName}
										onSelect={(value: any, option: any) => {
											treeSelect(value, option)
											setTenantryStatua(1)
										}}
									/>
								</Form.Item>
							</Col>

							<Col span={8}>
								<FormInput
									name="lessorName"
									label="出租方名称"
									disabled
									placeholder="选择所属公司自动带出"
									rules={[
										{
											required: true,
											message: '请选择出租方',
										},
									]}
								/>
							</Col>
							<Col span={8}>
								<FormRadio
									style={{width: '100%'}}
									label="承租方类型"
									rules={[
										{
											required: true,
											message: '请选择承租方类型',
										},
									]}
									items={lesseeType}
									name="lesseeType"
									disabled={
										orgStatus === 2 || tenantryStatua === 2
									}
									onChange={(value: any) => {
										clearUserInfo() // 清空之前的赋值
										setCodeStaue('1')
										setBDStaue('1')
										if (value?.target?.value === 1) {
											getDirveInfo('') // 获取司机列表
											setTenantryType(1)
											getChannelInfo('') // 切换成司机需要重新获取渠道列表
										} else if (value?.target?.value === 2) {
											const {query} = location
											const dataInfo = {
												id: query?.id,
												ord: query?.orgID,
											}
											getClueInfo(dataInfo) // 获取线索列表
											setTenantryType(2)

											// setChannelStatus(true)
										}
									}}
								/>
							</Col>
						</Row>
						<Row gutter={24}>
							<Col span={8}>
								{tenantryType === 1 ? (
									<Form.Item
										label="司机/线索名称"
										name="dirverInfo"
										rules={[{required: true}]}>
										<Select
											allowClear
											autoClearSearchValue
											showSearch
											value={valueNo}
											placeholder="请选择承租方"
											defaultActiveFirstOption={false}
											showArrow={false}
											filterOption={false}
											onSearch={handleSearch}
											onChange={handleChange}
											onClear={() => getDirveInfo('')}
											notFoundContent={null}
											fieldNames={{
												label: 'name',
												value: 'driverId',
											}}
											options={dirverInfo}
										/>
									</Form.Item>
								) : (
									<FormSelect
										filterOption
										label="司机/线索名称"
										name="dirverInfo"
										placeholder="请选择承租方"
										items={dirverInfo}
										keys="id"
										disabled={orgStatus === 2}
										title="username"
										rules={[
											{
												required: true,
												message: '请选择司机或线索',
											},
										]}
										onChange={(e: any, option: any) =>
											dirveChanges(e, option)
										}
									/>
								)}
							</Col>
							<Col span={8}>
								<FormInput
									name="customerName"
									label="客户名称"
									disabled
									placeholder="选择司机名称自动带出"
								/>
							</Col>
							<Col span={8}>
								<FormInput
									name="lesseeAddress"
									label="联系地址"
									disabled={tenantryType === 1}
									value={adress}
									placeholder="联系地址"
								/>
							</Col>
						</Row>
						<Row gutter={24}>
							<Col span={8}>
								<FormInput
									name="lesseeTel"
									label="联系电话"
									value={phone}
									disabled
								/>
							</Col>
							{channelState === '2' && (
								<Col span={8} className={styles.channel}>
									<FormSelect
										name="channelName"
										className={styles.select}
										label="渠道名称"
										items={channelList}
										keys="id"
										title="ditchName"
										disabled={
											!!(
												tenantryType === 2 ||
												orgStatus === 2
											)
										}
										placeholder="请选择渠道名称"
										rules={[
											{
												required: true,
												message: '请选择渠道名称',
											},
										]}
										onChange={(e: any, option: any) =>
											channelChange(e, option)
										}
									/>
								</Col>
							)}

							{BDStaue === '2' ? (
								<Col span={8} className={styles.channel}>
									<FormSelect
										name="channelBdName"
										className={styles.select}
										label="跟单BD"
										items={BDList}
										keys="id"
										disabled={BDstatus}
										title="ditchName"
										placeholder="请选择跟单BD"
										rules={[
											{
												required: true,
												message: '请选择跟单BD',
											},
										]}
										onChange={(e: any, option: any) =>
											BDChange(e, option)
										}
									/>
								</Col>
							) : (
								<></>
							)}
							{codeStaue === '2' ? (
								<Col span={8} className={styles.channel}>
									{codeType === 1 ? (
										<FormInput
											name="channelCode"
											label="渠道code码"
											disabled
											value={adress}
											placeholder="渠道code码"
											rules={[
												{
													required: true,
													message: '请选择渠道code码',
												},
											]}
										/>
									) : (
										<FormSelect
											name="channelCode"
											className={styles.select}
											label="渠道code码"
											items={codeList}
											keys="id"
											title="code"
											placeholder="请选择渠道code码"
											rules={[
												{
													required: true,
													message: '请选择渠道code码',
												},
											]}
											onChange={(e: any, option: any) =>
												form.setFieldsValue({
													channelCode: option?.code,
												})
											}
										/>
									)}
								</Col>
							) : (
								<></>
							)}
						</Row>
					</div>
					<div className={styles.goods}>
						<p className={styles.title}>
							<span>商品方案信息</span>
						</p>
						<Row>
							<Col span={6}>
								<Form.Item
									labelCol={{
										xs: {span: 24},
										sm: {span: 7},
									}}
									wrapperCol={{
										xs: {span: 24, offset: 0},
										sm: {span: 17, offset: 1},
									}}
									name="plan"
									label="选择商品方案"
									rules={[
										{
											required: true,
											message: '请选择商品方案',
										},
									]}>
									<Button
										onClick={() => {
											form.setFieldValue(
												'paymentMethod',
												1,
											)
											if (companyIds) {
												setSelectScheme(true)
											} else {
												message.error(
													'请先选择所属公司',
												)
											}
										}}>
										选择商品方案
									</Button>
								</Form.Item>
							</Col>
						</Row>
						{/* 如果没有选择方案，那么不展示列表 */}
						<div className={styles.selectedGoods}>
							<CustomTable
								key="id"
								dataSource={shoppingList}
								pagination={false}
								columns={columns}
								callback={() => {}}
							/>
						</div>
						<Col span={12} className={styles.payType}>
							<FormRadio
								labelCol={{
									xs: {span: 24},
									sm: {span: 3},
								}}
								wrapperCol={{
									xs: {span: 24, offset: 0},
									sm: {span: 23, offset: 1},
								}}
								style={{width: '100%'}}
								label="付款方式"
								rules={[
									{required: true, message: '请选择付款方式'},
								]}
								items={payType}
								name="paymentMethod"
							/>
						</Col>
						<Row>
							<Col span={6}>
								<FormTime
									subtype="date"
									labelCol={{
										xs: {span: 24},
										sm: {span: 7},
									}}
									wrapperCol={{
										xs: {span: 24, offset: 0},
										sm: {span: 19, offset: 1},
									}}
									disabled={startTimeState}
									name="startTime"
									rules={[
										{
											required: true,
											message: '请选择租赁日期',
										},
									]}
									label="租赁开始日"
									placeholder="请选择租赁开始日"
									onChange={timechange}
								/>
							</Col>
							<Col span={6} style={{marginLeft: '30px'}}>
								<FormInput
									name="endTime"
									labelCol={{
										xs: {span: 24},
										sm: {span: 5},
									}}
									wrapperCol={{
										xs: {span: 24, offset: 0},
										sm: {span: 19, offset: 1},
									}}
									disabled
									placeholder="自动计算"
									label="租赁结束日"
								/>
							</Col>
						</Row>
						<Row>
							<Col span={6}>
								<Form.Item
									labelCol={{
										xs: {span: 24},
										sm: {span: 5},
									}}
									wrapperCol={{
										xs: {span: 24, offset: 0},
										sm: {span: 21, offset: 1},
									}}
									label="付款日">
									按自然月账单生成
								</Form.Item>
							</Col>
						</Row>
						<Row>
							<Col span={8}>
								<FormInput
									name="remark"
									labelCol={{
										xs: {span: 24},
										sm: {span: 3},
									}}
									wrapperCol={{
										xs: {span: 24, offset: 0},
										sm: {span: 22, offset: 1},
									}}
									label="备注"
									rules={[
										{
											message: '请不要超过200个字符!',
											max: 200,
										},
									]}
									placeholder="请填写下单备注，不超过200个字符"
								/>
							</Col>
						</Row>
						<Row className={styles.footerBtn}>
							<Space>
								<Button
									shape="round"
									onClick={(e) => {
										e.stopPropagation()
										onCancel()
									}}>
									取消
								</Button>
								<Button
									shape="round"
									type="primary"
									htmlType="submit">
									提交
								</Button>
							</Space>
						</Row>
					</div>
				</Form>
				{companyIds && (
					<SelectScheme
						title="选择商品方案"
						isOpen={selectScheme}
						setIsOpen={setSelectScheme}
						selectOrder={selectOrder}
						orgIds={companyIds}
					/>
				)}
			</div>
		</Spin>
	)
}
export default connect(({global, user}: any) => ({global, user}))(AddOrder)
